package com.jumi.microservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.domain.vo.MessageUnreadVO;
import com.jumi.microservice.mapper.MessageAppMapper;
import com.jumi.microservice.mapper.MessageMailMapper;
import com.jumi.microservice.mapper.MessageSmsMapper;
import com.jumi.microservice.service.JPushService;
import com.jumi.microservice.service.MessageService;
import com.jumi.microservice.service.SmsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class MessageServiceImpl extends ServiceImpl<MessageMailMapper, MessageMail> implements MessageService {

    @Resource
    private MessageMailMapper messageMailMapper;
    @Resource
    private MessageSmsMapper messageSmsMapper;
    @Resource
    private MessageAppMapper messageAppMapper;
    @Resource
    private SmsService smsService;
    @Resource
    private JPushService jPushService;

    @Override
    public MessageUnreadVO SystemNewNum(Long uids) {
        MessageUnreadVO vo = messageMailMapper.selectUnread(uids);
        return vo;
    }

    @Override
    public MessageMail selectMessageId(Long id) {
        MessageMail messageMail = messageMailMapper.selectById(id);
        //判断是否能查到信息
        ExceptionEnum.FAIL_NULL.doThrowIf(messageMail ==null);
        if(messageMail.getMessageOpen() == 0){
            //未读改为已读
            messageMail.setMessageOpen(1);
            messageMailMapper.updateById(messageMail);
        }
        return messageMail;
    }

    @Override
    public void readMessage(Long id) {
        MessageMail messageMail = messageMailMapper.selectById(id);
        //判断是否能查到信息
        ExceptionEnum.FAIL_NULL.doThrowIf(messageMail ==null);
        //改为已读状态
        messageMail.setMessageOpen(1);
        messageMailMapper.updateById(messageMail);
    }

    /**
     * 站内信消息传输类
     * @param mail
     * @return
     */
    @Override
    public Long messageSend(MessageMail mail) {
        MessageMail messageMail = new MessageMail();
        //消息模板id
        messageMail.setTemplateId(mail.getTemplateId());
        //1：交易物流通知,2：商品活动通知,3：系统消息通知,4：余额变动通知
        messageMail.setTemplateTitleType(mail.getTemplateTitleType());
        //发送人
        messageMail.setSdMemberId(mail.getSdMemberId());
        //接收人
        messageMail.setReMemberId(mail.getReMemberId());
        //站内信内容
        messageMail.setMessageContent(mail.getMessageContent());
        //图片地址
        messageMail.setMessageImg(mail.getMessageImg());
        //h5跳转地址
        messageMail.setLink(mail.getLink());
        messageMailMapper.insert(messageMail);

        return messageMail.getMessageId();
    }

    /**
     * 极光推送消息传输类
     * @param app
     * @return
     */
    @Override
    public Long messageSend(MessageApp app,MessageBody body,Integer unreadNum) {
        app.setAppLink(JSONObject.toJSONString(body.getLink()));
        Map<String,String> like = body.getLink();
        //设备id
        like.put("id", app.getAppRegisterid());
        //模板名称
        like.put("title", app.getAppTitle());
        //app模板内容
        like.put("msg", app.getAppContent());
        //未读消息
        like.put("unread_message_num", unreadNum.toString());
        //获取安卓厂家跳转地址
        String  uri_address = uriAddress(like.get("type"));
        //华为手机厂商跳转页面-只针对android手机
        like.put("uri_activity",uri_address);
        //OPPO手机厂商跳转页面-只针对android手机
        like.put("uri_action",uri_address);
        //执行推送
        String result =  jPushService.pushAll(like,unreadNum);
        Integer code = 200;
        if(result != null){
            JSONObject o = JSONObject.parseObject(result);
            if(!"0".equals(o.getString("statusCode"))){
                code = 500;
            }
        } else {
            code = 500;
        }
        //加入app发送日志
        app.setAppCode(code);
        messageAppMapper.insert(app);
        return app.getAppId();
    }

    private String uriAddress(String type){
        String uri_address = "";
        switch (type){
            case "1":
                uri_address = "com.jumi.groupbuy.Activity.order.OrderDetailStateActivity";
                break;
            case "2":
                uri_address = "com.jumi.groupbuy.Activity.order.OrderDetailStateActivity";
                break;
            case "3":
                uri_address = "com.jumi.groupbuy.Activity.order.OrderDetailStateActivity";
                break;
            case "4":
                uri_address = "com.jumi.groupbuy.Activity.logistics.LogisticsOneActivity";
                break;
            case "5":
                uri_address = "com.jumi.groupbuy.Activity.logistics.LogisticsOneActivity";
                break;
            case "6":
                uri_address = "com.jumi.groupbuy.Activity.order.OrderDetailStateActivity";
                break;
            case "7":
                uri_address = "com.jumi.groupbuy.Activity.logistics.LogisticsOneActivity";
                break;
            case "8":
                uri_address = "com.jumi.groupbuy.Activity.aftersale.AfterSaleActivity";
                break;
            case "9":
                uri_address = "com.jumi.groupbuy.Activity.aftersale.AfterSaleActivity";
                break;
            case "10":
                uri_address = "com.jumi.groupbuy.Activity.logistics.LogisticsOneActivity";
                break;
            case "11":
                uri_address = "com.jumi.groupbuy.Activity.Customer_managementActivity";
                break;
            case "12":
                uri_address = "com.jumi.groupbuy.Activity.MainActivity";
                break;
            case "13":
                uri_address = "com.jumi.groupbuy.Activity.Customer_managementActivity";
                break;
            case "14":
                uri_address = "com.jumi.groupbuy.Activity.Cumulative_detailsActivity";
                break;
            case "15":
                uri_address = "com.jumi.groupbuy.Activity.Cumulative_detailsActivity";
                break;
            case "16":
                uri_address = "com.jumi.groupbuy.Activity.IncomeDetailsActivity";
                break;
            case "17":
                uri_address = "com.jumi.groupbuy.Activity.setup.FeedBackListActivity";
                break;
            case "18":
                uri_address = "com.jumi.groupbuy.Activity.WithdrawalamoutActivity";
                break;
            case "19":
                uri_address = "com.jumi.groupbuy.Activity.WithdrawalamoutActivity";
                break;
            case "20":
                uri_address = "com.jumi.groupbuy.Activity.WithdrawalamoutActivity";
                break;
            default:
                uri_address = "";
        }
        return uri_address;
    }

    /**
     * 极光推送所有用户消息传输类
     * @param app
     * @return
     */
    @Override
    public Boolean messageSend(AppMessageAll app) {
        JSONObject json = new JSONObject();
        //消息列表id
        json.put("messageId",String.valueOf(app.getMessageId()));
        //跳转类型
        json.put("type", "-1");
        //模板名称
        json.put("title", app.getTitle());
        //app模板内容
        json.put("msg", app.getMessageContent());
        if(app.getSpuId() == 0){
            //商品supid
            json.put("spuId", "");
            //华为手机厂商跳转页面-只针对android手机
            json.put("uri_activity","");
            //OPPO手机厂商跳转页面-只针对android手机
            json.put("uri_action","");
        }else{
            //商品supid
            json.put("spuId", String.valueOf(app.getSpuId()));
            //华为手机厂商跳转页面-只针对android手机
            json.put("uri_activity","com.jumi.groupbuy.Activity.WebviewActivity");
            //OPPO手机厂商跳转页面-只针对android手机
            json.put("uri_action","com.jumi.groupbuy.Activity.WebviewActivity");
        }
        System.err.println("极光推送所有用户消息传输类json:"+json);
        Map params = (Map)json;
        String result =  jPushService.pushUserAll(params);
        if(result != null){
            JSONObject o = JSONObject.parseObject(result);
            if(!"0".equals(o.getString("statusCode"))){
                return Boolean.FALSE;
            }
        } else {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    /**
     * 短信传输类
     * @param sms
     * @return
     */
    @Override
    public Long messageSend(MessageSms sms) {
        SendSms sendSms = new SendSms();
        //手机号
        sendSms.setPhoneNumbers(sms.getSmtPhone());
        //短信模版id
        sendSms.setTemplateCode(sms.getSmtShortId());
        //短信模板变量替换参数
        sendSms.setTemplateParam(sms.getSmtParameter());

        String result = smsService.send(sendSms);

        Integer code = 200;
        if(result != null){
            JSONObject o = JSONObject.parseObject(result);
            if(!"OK".equals(o.getString("Message"))  || !"OK".equals(o.getString("Code")) ){
                code = 500;
            }
        } else {
            code = 500;
        }
        //0:设备统一发送,1:短信单独发送
        sms.setSmtType(sms.getSmtType());
        //200:成功,500:失败
        sms.setSmtCode(code);
        //错误信息
        sms.setSmtMessage(result);
        messageSmsMapper.insert(sms);
        return sms.getSmsId();
    }

    /**
     * 微信公众号消息传输类
     * @param weChatMessage
     * @return
     */
    @Override
    public Boolean messageSend(WeChatMessage weChatMessage) {
        return null;
    }

    /**
     * 微信小程序传输类
     * @param weChatAppletsMessage
     * @return
     */
    @Override
    public Boolean messageSend(WeChatAppletsMessage weChatAppletsMessage) {
        return null;
    }
}
